#!/bin/sh
filepath=$(cd "$(dirname "$0")"; pwd)
. rt.comm
rt_init
if [ -z "$1" ];then
    echo "Please input the file to rsync. "
    exit 0
fi

dst_reverse=0
if [ "$2" == "-r" ];then
    dst_reverse=1
fi
if [ "$1" == "-r" ];then
    dst_reverse=1
fi

if [ "$dst_reverse" == "1" ];then
    for i in `seq 1 $#`
    do
        dst_file="$(eval echo "\$$i")";
        if [ "$dst_file" != "-r" ];then

            config_cont=`rtinfo "$dst_file"`
            if [ "$config_cont" == "" ]; then 
                rt_noconf
                exit 0  
            fi
            rt_exec `echo "$config_cont"`

            START=`date +%s%N`
            TMP_DIR="/tmp/rt$START"
            echo "expect $filepath/rtr.expect \"$jump_ip\" \"$jump_port\" \"$jump_user\" \"$jump_tmpdir\" \"$dst_ip\" \"$dst_port\" \"$dst_dir\" \"$dst_user \"$dst_file\" \"rt$START\""
            expect $filepath/rtr.expect "$jump_ip" "$jump_port" "$jump_user" "$jump_tmpdir" "$jump_pwd" "$dst_ip" "$dst_port" "$dst_dir" "$dst_user" "$dst_pwd" "$dst_file" "rt$START" | grep -P "(sent.*bytes)|(file.*to consider)|(rsync error)"
            #expect $filepath/rtr.expect "$jump_ip" "$jump_port" "$jump_user" "$jump_tmpdir" "$jump_pwd" "$dst_ip" "$dst_port" "$dst_dir" "$dst_user" "$dst_pwd" "$dst_file" "rt$START"
            END=`date +%s%N`
            echo rtr used :`expr $END - $START` nanoseconds
        fi
    done
else
    for i in `seq 1 $#`
    do
        dst_file="$(eval echo "\${$i}")";

        config_cont=`rtinfo "$dst_file"`
        if [ "$config_cont" == "" ]; then 
            rt_noconf
            exit 0  
        fi
        rt_exec `echo "$config_cont"`

        START=`date +%s%N`
        TMP_DIR="/tmp/rt$START"
        mkdir -p $TMP_DIR
        #echo /usr/bin/rsync -a "$dst_file" $TMP_DIR/
        /usr/bin/rsync -a "$dst_file" $TMP_DIR/
        dst_file=$TMP_DIR/`basename $dst_file`
        echo "expect $filepath/rt.expect \"$jump_ip\" \"$jump_port\" \"$jump_user\" \"$jump_tmpdir\" \"$dst_ip\" \"$dst_port\" \"$dst_dir\" \"$dst_user\" \"$dst_file\" \"rt$START\""
        expect $filepath/rt.expect "$jump_ip" "$jump_port" "$jump_user" "$jump_tmpdir" "$jump_pwd" "$dst_ip" "$dst_port" "$dst_dir" "$dst_user" "$dst_pwd" "$dst_file" "rt$START" | grep -P "(sent.*bytes)|(file.*to consider)|(rsync error)"
        #expect $filepath/rt.expect "$jump_ip" "$jump_port" "$jump_user" "$jump_tmpdir" "$jump_pwd" "$dst_ip" "$dst_port" "$dst_dir" "$dst_user" "$dst_pwd" "$dst_file" "rt$START" 
        rm $TMP_DIR -rf
        END=`date +%s%N`
        echo rt used :`expr $END - $START` nanoseconds
    done
fi

exit 0
